<?php
class MemcachedUtility
{
    /**
     * @var Memcached
     */
    private static $_client;

    /**
     * @return Memcached
     */
    public static function getClient()
    {
        if(self::$_client === null)
        {
            self::$_client = new Memcached();
            self::$_client->addServers(Yii::app()->params[ENUM_CONFIG_PARAM_MEMCACHED_SERVERS]);
            self::$_client->setOption(Memcached::OPT_COMPRESSION, false);
        }
        return self::$_client;
    }

    public static function get($key, $default = null)
    {
        $client = self::getClient();
        $val = $client->get($key);
        if($client->getResultCode() ==  Memcached::RES_NOTFOUND)
        {
            return $default;
        }
        return $val;
    }

    public static function set($key, $val, $expire = 0)
    {
        if($expire)
        {
            $expire = time() + $expire;
        }
        self::getClient()->set($key, $val, $expire);
    }

    public static function add($key, $val, $expire = 0)
    {
        if($expire)
        {
            $expire = time() + $expire;
        }
        self::getClient()->add($key, $val);
    }

    public static function append($key, $val)
    {
        $client = self::getClient();
        $client->append($key, $val);
        if($client->getResultCode() ==  Memcached::RES_NOTSTORED)
        {
            $client->add($key, $val);
        }
    }

    public static function delete($key)
    {
        self::getClient()->delete($key);
    }
}
